const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require("path");
const pre_project = "sua/";
module.exports = {
  eslint: {
    enable: false, // 关闭 ESLint
    mode: "off"    // 可选，显式声明关闭模式
  },
  webpack: {
    alias: {
      "@": path.resolve(__dirname, "src"),
      "@assets": path.resolve(__dirname, "src/resource"),
      "@helpers": path.resolve(__dirname, "src/helpers")
    },
    configure: (webpackConfig) => {
      webpackConfig.devtool = false;

      // 移除 ESLint Loader
      webpackConfig.module.rules = webpackConfig.module.rules.filter(rule => {
        return !(rule.loader && rule.loader.includes("eslint-loader"));
      });
      webpackConfig.module.rules.push({
        test: /\.(png|jpe?g|gif|svg|woff2?|ttf|json)$/,
        type: 'asset/resource',
        generator: {
          filename: pre_project + 'static/media/[name].[hash:8][ext]',
        },
      });

      webpackConfig.cache.type = "filesystem";
      webpackConfig.optimization = {
        ...webpackConfig.optimization,
        minimize: true,
        splitChunks: {
          chunks: 'all',
          cacheGroups: {
            vendor: {
              test: /[\\/]node_modules[\\/]/,
              name: 'vendor',
              chunks: 'all',
              filename: pre_project + 'static/js/vendor.[contenthash:8].js',
            },
          },
        },
      };
      webpackConfig.output = {
        ...webpackConfig.output,
        filename:pre_project +  'static/js/[name].[contenthash:8].js', // 主 JS 文件
        chunkFilename: pre_project + 'static/js/[name].[contenthash:8].chunk.js', // 按需加载的 JS
      };

      webpackConfig.plugins = [
        ...webpackConfig.plugins.filter(t=> {
          if (t instanceof MiniCssExtractPlugin) return false;
            return true;
        }),
        new MiniCssExtractPlugin({
          filename:pre_project +  'static/css/[name].[contenthash:8].css',
          chunkFilename: pre_project + 'static/css/[id].[contenthash:8].css',
        }),
      ];
      
      // 构建分析
      return webpackConfig;
    },
    devServer: {
      setupMiddlewares: function(middlewares, devServer) {
        if (fs.existsSync(paths.proxySetup)) {
          require(paths.proxySetup)(devServer.app)
        }
        
        middlewares.push(
            evalSourceMapMiddleware(devServer),
            redirectServedPath(paths.publicUrlOrPath),
            noopServiceWorkerMiddleware(paths.publicUrlOrPath)
        )
        
        return middlewares;
      },
    }
  },
  devServer: (devServerConfig, { env, paths, proxy, allowedHost }) => {
    delete devServerConfig.onBeforeSetupMiddleware
    delete devServerConfig.onAfterSetupMiddleware
    return devServerConfig
  },
  maxWorkers: 8
}